package spt.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBAdapter {
	private static final Logger log = Logger.getLogger(DBAdapter.class.getName());
	
	/**
	 * Returns connection to database from connection pool. Database is 
	 * accessible by JNDI.
	 * @return Connection to database
	 */
	public static Connection getConnection(){
		Context initCtx;
		try {
			initCtx = new InitialContext();
			DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/sptdb");

			return ds.getConnection();
		} catch (NamingException e) {
			log.severe(e.getMessage());
		} catch (SQLException e) {
			log.severe(e.getMessage());
		}
		return null;
	}
	
	/**
	 * Safety closes statement and connection to database.
	 * @param connection Connection to close.
	 * @param statement Statement to close.
	 */
	public static void closeConnection(Connection connection, Statement statement){
		try {
			if(statement != null)
				statement.close();
		} catch (SQLException e) {
			log.severe(e.getMessage());
		} finally{
			try {
				if(connection != null)
					connection.close();
			} catch (SQLException e) {
				log.severe(e.getMessage());
			}
		}
	}
	
	/**
	 * Safety closes result set, statement and connection to database.
	 * @param connection Connection to close.
	 * @param statement Statement to close.
	 * @param resultSet ResultSet to close.
	 */
	public static void closeConnection(Connection connection, Statement statement, ResultSet resultSet){
		try{
			if(resultSet != null)
				resultSet.close();
		}catch(SQLException e){
			log.severe(e.getMessage());
		} finally{
			try {
				if(statement != null)
					statement.close();
			} catch (SQLException e) {
				log.severe(e.getMessage());
			} finally {
				try {
					if(connection != null)
						connection.close();
				} catch (SQLException e) {
					log.severe(e.getMessage());
				}
			}
		}
	}
}
